package com.pengbei.enshrine.ui.main;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import androidx.annotation.Nullable;
import androidx.appcompat.widget.Toolbar;

import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.pengbei.enshrine.R;
import com.pengbei.enshrine.base.BaseActivity;

public class WebActivity extends BaseActivity {

    private TitleBar tb_web;
    private WebView wv_web;
    private String title = "";
    private String url = "";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_web);
        initView();
    }

    private void initView() {
        title = getIntent().getStringExtra("title");
        url = getIntent().getStringExtra("url");

        tb_web = (TitleBar) findViewById(R.id.tb_web);
        wv_web = findViewById(R.id.wv_web);

        if(!TextUtils.isEmpty(title)){
            tb_web.setTitle(title);
        }

        tb_web.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(TitleBar titleBar) {
                if (wv_web.canGoBack()) {
                    wv_web.goBack();
                }else {
                    finish();
                }
            }
        });

        showWebView(url);
    }


    private void showWebView(String url) {
        System.out.println("==========url======"+url);
        wv_web.removeJavascriptInterface("searchBoxJavaBridge_");
        wv_web.removeJavascriptInterface("accessibility");
        wv_web.removeJavascriptInterface("accessibilityTraversal");
        wv_web.clearCache(true);
        wv_web.getSettings().setJavaScriptEnabled(true); // 启用JavaScript支持（可选）
        wv_web.loadUrl(url);
        wv_web.setWebViewClient(new WebViewClient());
    }


    public static void goToThisActivity(Context context, String title, String url) {
        Intent intent = new Intent();
        intent.setClass(context, WebActivity.class);
        intent.putExtra("title",title);
        intent.putExtra("url",url);
        context.startActivity(intent);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK) && wv_web.canGoBack()) {
            if (wv_web.canGoBack()) {
                wv_web.goBack();
            }else {
                finish();
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}